//
//  SWRefreshControl.swift
//  MYSwiftWeiBo
//
//  Created by shingwai chan on 16/3/6.
//  Copyright © 2016年 ChanShingWai. All rights reserved.
//

import UIKit

class SWRefreshControl: UIRefreshControl {

    
    let refreshControlOffSet = CGFloat(-60)
    
    // 箭头标示符
    private var isUp = false
    //重写父类的frame来判断是否显示刷新
    override var frame: CGRect {
        didSet{
//            print("frame: \(frame.origin)")
            //向上拖
            if frame.origin.y > 0{
                return
            }
            //这里就是向下拖 y比-60小
            if frame.origin.y <= refreshControlOffSet && isUp == false {
                isUp = true
                refreshView.ratotionTipIcon(isUp)
            }
            else if frame.origin.y > refreshControlOffSet && isUp {
                //比-60大 箭头向上时 这时是向上拖
                //这时箭头要向下
                isUp = false
                refreshView.ratotionTipIcon(isUp)
            }
            //正在加载
            if refreshing {
                refreshView.startLoading()
            }
        }
    }
    
    /**
     当tabView复位时 停止动画
     */
    override func endRefreshing() {
        super.endRefreshing()
        refreshView.stopLoading()
    }
    
    override init() {
        
        super.init()
        
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //设置ui
    func setUpUI() {
        
        addSubview(refreshView)
        //添加约束
        refreshView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self)
            make.size.equalTo(refreshView.bounds.size)
        }
    
    }
    //懒加载
    lazy var refreshView = SWRefreshView.refreshView()
}



//MARK: -- 刷新view
class SWRefreshView: UIView {
    
    //菊花
    @IBOutlet weak var loading: UIImageView!
    //加载时隐藏箭头 的SuperView
    @IBOutlet weak var tipView: UIView!
    //箭头
    @IBOutlet weak var tipIcon: UIImageView!
    
    @IBOutlet weak var refLabel: UILabel!
    class func refreshView() -> SWRefreshView {
        //从xib中加载
        let view = NSBundle.mainBundle().loadNibNamed("SWRefreshView", owner: nil, options: nil).last as! SWRefreshView
        return view
    }
    
    /**
     箭头旋转
     
     - parameter isUp: 是否向上
     */
    func ratotionTipIcon(isUp: Bool) {
        refLabel.text = isUp ? "释放更新" : "下拉刷新" 
        UIView.animateWithDuration(0.25) { () -> Void in
            //判断是否向上 选转箭头
            self.tipIcon.transform = isUp ? CGAffineTransformMakeRotation(CGFloat(M_PI - 0.001)) : CGAffineTransformIdentity
        }
    }
    
    /**
     菊花转
     */
    func startLoading () {
    
        let animationKey = "rotationAnim"
        //判断是否重复添加动画
        if let _ = loading.layer.animationForKey(animationKey) {
//            print("已添加动画")
            return
        }
        //隐藏箭头
        tipView.hidden = true
        //创建基础动画
        let rotationAnim = CABasicAnimation(keyPath: "transform.rotation")
        rotationAnim.toValue = M_PI * 2 // 动画数值
        rotationAnim.repeatCount = MAXFLOAT //重复次数
        rotationAnim.duration = 0.25//动画秒数
        rotationAnim.removedOnCompletion  = false //不移除
        //loadingView添加动画
        loading.layer.addAnimation(rotationAnim, forKey: animationKey)
    }
    
    /**
     停止菊花转
     */
    func stopLoading() {
        //移除动画
        loading.layer.removeAllAnimations()
        //显示箭头
        tipView.hidden = false
    }
    
    
}